﻿using Serilog;
using Serilog.Core;
using Serilog.Events;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Threading;
using System.Threading.Tasks;
using WatchDog.WatchItemManages;

namespace WatchDog.WinService
{
    public partial class Service1 : ServiceBase
    {
 
        private readonly string _strAssemblyDirPath = string.Empty;
        private readonly BackgroundJob _backgroundJob;
        public Service1()
        {
            InitializeComponent();

            string strAssemblyFilePath = Assembly.GetExecutingAssembly().Location;
            _strAssemblyDirPath = Path.GetDirectoryName(strAssemblyFilePath);
 
            _backgroundJob = new BackgroundJob(_strAssemblyDirPath);
        }
 
        protected override void OnStart(string[] args)
        {
            Log.Logger.Information("正在启动服务...");

            _backgroundJob?.Start(); 
        }

        protected override void OnStop()
        {
            Log.Logger.Information("正在停止服务...");

            _backgroundJob?.Stop();
        }

        private void Restart()
        {
            _backgroundJob?.Restart();
        }

        protected override void OnCustomCommand(int command)
        {
            base.OnCustomCommand(command);

            // Depending on the integer passed in, the appropriate method is called.
            switch (command)
            {
                case (int)WindowsServiceCustomCommands.ServiceLogLevelDebug:
                    Serilog.loggingLevelSwitch.MinimumLevel = LogEventLevel.Debug;
                    _backgroundJob.Logger.Debug("接收到控制程序端日志变更指令，日志记录等级变更为 诊断模式");
                    break;
                case (int)WindowsServiceCustomCommands.ServiceLogLevelWarning:
                    _backgroundJob.Logger.Debug("接收到控制程序端日志变更指令，日志记录等级变更为 生产模式");
                    Serilog.loggingLevelSwitch.MinimumLevel = LogEventLevel.Warning;
                    break;
                case (int)WindowsServiceCustomCommands.WatchItemChanged:
                    _backgroundJob.Logger.Debug("接收到控制程序端监控配置更改通知，将执行清除缓存和计划任务...");
                    Restart();
                    break;
                default:
                    break;
            }
        }
    }
}
